package com.cloudspace.jindun.fragment;


import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.Woyao.CellActivitye;
import com.cloudspace.jindun.activity.Woyao.PassActivitye;
import com.cloudspace.jindun.activity.Woyao.SystemSettingsActivity;
import com.cloudspace.jindun.model.UserInfoResult;
import com.cloudspace.jindun.net.manager.ImageManager;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.ui.CircleImageView;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.BitmapUtil;
import com.cloudspace.jindun.utils.FileUtil;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.window.SelectPicPopupWindow;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class MenuLeftFragment extends Fragment {


    @Bind(R.id.wd_collect_rl)
    RelativeLayout mWdCollectRl;
    @Bind(R.id.wd_text_phoneNum)
    TextView mWdTextPhoneNum;
    @Bind(R.id.wd_collect_r2)
    RelativeLayout mWdCollectR2;
    @Bind(R.id.wd_collect_r3)
    RelativeLayout mWdCollectR3;
    @Bind(R.id.wd_collect_r4)
    RelativeLayout mWdCollectR4;
    @Bind(R.id.wd_image_head)
    CircleImageView mWdImageHead;
    @Bind(R.id.wd_text_name)
    TextView mWdTextName;

    private SelectPicPopupWindow menuWindow;
    private String sign = "menu";

    private String userId;
    private String filename = "ico.png";
    private File file;

    public MenuLeftFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_menu_left, container, false);
        ButterKnife.bind(this, view);
        initData();


        return view;
    }

    private void initData() {
        if (UserSessionManager.getCurrentLoginUser().getUserName() != null) {
            mWdTextName.setText(UserSessionManager.getCurrentLoginUser().getUserName());
        }
        if (UserSessionManager.getCurrentLoginUser().getUserId() != null) {
            userId = UserSessionManager.getCurrentLoginUser().getUserId();
        }
        if (UserSessionManager.getCurrentLoginUser().getIconUrl() != null) {
            String iconUrl = UserSessionManager.getCurrentLoginUser().getIconUrl();
            ImageManager.loadCircleImage(getContext(), mWdImageHead, iconUrl);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bitmap bitmap = null;
            try {
                if (requestCode == 1) {
                    Uri selectedImage = data.getData();
                    bitmap = BitmapFactory.decodeStream(getActivity()
                            .getContentResolver().openInputStream(Uri.parse(selectedImage.toString())));
                } else if (requestCode == 2) {
                    if (data.getExtras() != null) {
                        Bundle bundle = data.getExtras();
                        bitmap = (Bitmap) bundle.get("data");//
                    }
                }

                saveAndUploadImage(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            ToastMaker.showToastShort(R.string.not_choose_picture);
        }
    }

    private final String FILE_SAVE_NAME = "icon.png";

    @Nullable
    private void saveAndUploadImage(Bitmap bitmap) throws FileNotFoundException {
        if (ObjUtil.isEmpty(bitmap)){
            ToastMaker.showToastShort(R.string.select_photo_error);
        }

        String filePath = FileUtil.getLocalFileImagePath() + FILE_SAVE_NAME;
        if ((filePath = BitmapUtil.compressImage(getContext(), bitmap, filePath, 20)) == null) {
            ToastMaker.showToastShort(R.string.select_photo_error);
        }

        file = new File(filePath);
        mWdImageHead.setImageBitmap(bitmap);

        requestData(YXHttpUrl.WD_GHTX_URI, userId, filePath, file);
    }

    public Dialog showDialog(final Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.alert_dialogmenu, null);

        final Dialog dialog = new AlertDialog.Builder(context).setView(view).create();

        dialog.show();
        Button take = (Button) view.findViewById(R.id.btn_take_photo);
        Button pick = (Button) view.findViewById(R.id.btn_pick_photo);
        final Button cancel = (Button) view.findViewById(R.id.btn_cancel);
        take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(intent2, 2);
                } else {
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(intent2, 2);
                }
                dialog.dismiss();

            }
        });
        pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //intent = new Intent(Intent.ACTION_GET_CONTENT);
                /* 开启Pictures画面Type设定为image */
                intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                startActivityForResult(intent, 1);
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        return dialog;
    }

    @Override
    public void onResume() {
        super.onResume();

        mWdTextPhoneNum.setText(UserSessionManager.getCurrentLoginUser().getUserName());
        mWdTextPhoneNum.setText(UserSessionManager.getCurrentLoginUser().getUserPhone());
    }

    @OnClick({R.id.wd_collect_rl, R.id.wd_collect_r2, R.id.wd_collect_r3, R.id.wd_collect_r4})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.wd_collect_rl:
                showDialog(getContext());
                break;
            case R.id.wd_collect_r2:
                Intent intentCall = new Intent();
                intentCall.setClass(getContext(), CellActivitye.class);
                intentCall.putExtra("sign", sign);
                startActivity(intentCall);
                break;
            case R.id.wd_collect_r3:
                Intent intentPass = new Intent();
                intentPass.setClass(getContext(), PassActivitye.class);
                intentPass.putExtra("sign", sign);
                startActivity(intentPass);
                break;
            case R.id.wd_collect_r4:
                Intent intentSys = new Intent();
                intentSys.setClass(getContext(), SystemSettingsActivity.class);
                intentSys.putExtra("sign", sign);
                startActivity(intentSys);
                break;
        }
    }

    private void requestData(String url, String userId, String filename, File file) {
        OkHttpUtils.post()
                .addFile("files", filename, file)
                .url(url)
                .addParams("userId", userId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.generic_error);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            Gson gson = new Gson();
                            UserInfoResult result = gson.fromJson(response, UserInfoResult.class);
                            if (result != null && result.status == 200) {
                                UserSessionManager.updateUserInfo(result.data);
                                ToastMaker.showToastShort(R.string.update_photo_success);
                            } else {
                                ToastMaker.showToastShort(R.string.update_photo_fail);
                            }
                        }
                    }
                });
    }
}
